<template>
  <div class="dashboard-view">
    <h1>数据统计看板</h1>
    
    <div v-if="isLoading" class="loading-container">
      <el-skeleton :rows="3" animated />
    </div>
    
    <template v-else>
      <div class="dashboard-summary">
        <div class="summary-card">
          <h3>总待办事项</h3>
          <div class="summary-value">{{ statistics?.totalTasks || 0 }}</div>
        </div>
        
        <div class="summary-card">
          <h3>已完成事项</h3>
          <div class="summary-value">{{ statistics?.completedTasks || 0 }}</div>
        </div>
        
        <div class="summary-card">
          <h3>完成率</h3>
          <div class="summary-value">{{ completionRateFormatted }}</div>
        </div>
        
        <div class="summary-card">
          <h3>逾期任务</h3>
          <div class="summary-value">{{ statistics?.overdueTasks || 0 }}</div>
        </div>
      </div>
      
      <div class="charts-container">
        <div class="chart-card">
          <h3>完成率趋势</h3>
          <div ref="completionTrendChart" class="chart"></div>
        </div>
        
        <div class="chart-card">
          <h3>分类占比</h3>
          <div ref="categoryPieChart" class="chart"></div>
        </div>
        
        <!-- <div class="chart-card">
          <h3>优先级分布</h3>
          <div ref="priorityChart" class="chart"></div>
        </div> -->
      </div>
    </template>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount, nextTick } from 'vue'
import { useTodoStore } from '../stores/todo'
import * as echarts from 'echarts/core'
import { LineChart, PieChart, BarChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'

// 注册必要的组件
echarts.use([
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  LineChart,
  PieChart,
  BarChart,
  CanvasRenderer
])

const todoStore = useTodoStore()
const completionTrendChart = ref(null)
const categoryPieChart = ref(null)
const priorityChart = ref(null)
const isLoading = ref(true)
const statistics = ref(null)
const productivityData = ref(null)

let trendChartInstance = null
let pieChartInstance = null
let priorityChartInstance = null

const completionRateFormatted = computed(() => {
  return `${statistics.value?.completionRate || 0}%`
})

const initCompletionTrendChart = () => {
  if (!completionTrendChart.value) {
    console.error('趋势图表DOM元素不存在')
    return
  }
  
  if (!productivityData.value || !Array.isArray(productivityData.value)) {
    console.error('趋势数据不存在或格式不正确:', productivityData.value)
    return
  }
  
  console.log('初始化趋势图表，数据:', productivityData.value)
  
  const labels = []
  const completionRates = []
  
  // 处理后端返回的数据格式
  productivityData.value.forEach(item => {
    labels.push(item.date)
    completionRates.push(item.completionRate)
  })
  
  console.log('处理后的趋势图表数据:', { labels, completionRates })
  
  // 如果已经存在图表实例，先销毁
  if (trendChartInstance) {
    trendChartInstance.dispose()
  }
  
  trendChartInstance = echarts.init(completionTrendChart.value)
  const option = {
    title: {
      text: '完成率趋势',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: labels
    },
    yAxis: {
      type: 'value',
      min: 0,
      max: 100,
      axisLabel: {
        formatter: '{value}%'
      }
    },
    series: [
      {
        name: '完成率',
        type: 'line',
        data: completionRates,
        smooth: true,
        lineStyle: {
          width: 3,
          color: '#409EFF'
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: 'rgba(64, 158, 255, 0.5)' },
              { offset: 1, color: 'rgba(64, 158, 255, 0.1)' }
            ]
          }
        }
      }
    ]
  }
  
  trendChartInstance.setOption(option)
}

const initCategoryPieChart = () => {
  if (!categoryPieChart.value) {
    console.error('分类饼图DOM元素不存在')
    return
  }
  
  if (!statistics.value || !statistics.value.categoryDistribution) {
    console.error('分类分布数据不存在:', statistics.value)
    return
  }
  
  console.log('初始化分类饼图，数据:', statistics.value.categoryDistribution)
  
  const categoryData = statistics.value.categoryDistribution.map(category => {
    return {
      name: category.name,
      value: category.count
    }
  })
  
  console.log('处理后的分类饼图数据:', categoryData)
  
  // 如果已经存在图表实例，先销毁
  if (pieChartInstance) {
    pieChartInstance.dispose()
  }
  
  pieChartInstance = echarts.init(categoryPieChart.value)
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      top: 'center'
    },
    series: [
      {
        name: '分类占比',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '14',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: categoryData
      }
    ]
  }
  
  pieChartInstance.setOption(option)
}

const initPriorityChart = () => {
  if (!priorityChart.value) {
    console.error('优先级图表DOM元素不存在')
    return
  }
  
  console.log('初始化优先级图表')
  
  // 如果已经存在图表实例，先销毁
  if (priorityChartInstance) {
    priorityChartInstance.dispose()
  }
  
  // 创建一个空的图表
  priorityChartInstance = echarts.init(priorityChart.value)
  const option = {
    title: {
      text: '优先级分布 (暂无数据)',
      left: 'center'
    },
    tooltip: {
      trigger: 'item'
    },
    series: [
      {
        name: '优先级分布',
        type: 'bar',
        data: []
      }
    ]
  }
  
  priorityChartInstance.setOption(option)
}

const handleResize = () => {
  console.log('窗口大小变化，重新调整图表大小')
  
  if (trendChartInstance) {
    trendChartInstance.resize()
  }
  
  if (pieChartInstance) {
    pieChartInstance.resize()
  }
  
  if (priorityChartInstance) {
    priorityChartInstance.resize()
  }
}

const fetchStatisticsData = async () => {
  isLoading.value = true
  try {
    // 获取任务统计数据
    const statsResponse = await todoStore.getTaskStatistics()
    console.log('统计数据响应:', statsResponse)
    
    if (statsResponse && statsResponse.code === 0) {
      statistics.value = statsResponse.data || {
        totalTasks: 0,
        completedTasks: 0,
        pendingTasks: 0,
        overdueTasks: 0,
        completionRate: 0
      }
    }
    
    // 获取生产力趋势数据
    const prodResponse = await todoStore.getProductivityTrend()
    console.log('生产力趋势响应:', prodResponse)
    
    if (prodResponse && prodResponse.code === 0) {
      productivityData.value = prodResponse.data || []
    }
    
    // 获取分类分布数据
    const categoryResponse = await todoStore.getCategoryDistribution()
    console.log('分类分布响应:', categoryResponse)
    
    if (categoryResponse && categoryResponse.code === 0) {
      statistics.value = {
        ...statistics.value,
        categoryDistribution: categoryResponse.data || []
      }
    }
    
    // 使用nextTick确保DOM已更新后再初始化图表
    await nextTick()
    console.log('初始化图表，数据状态:', {
      statistics: statistics.value,
      productivityData: productivityData.value
    })
    
    // 初始化图表
    initCompletionTrendChart()
    initCategoryPieChart()
    initPriorityChart()
  } catch (error) {
    console.error('获取统计数据失败:', error)
  } finally {
    isLoading.value = false
  }
}

onMounted(async () => {
  await fetchStatisticsData()
  
  // 添加一个小延迟，确保DOM已完全渲染
  setTimeout(() => {
    console.log('延迟初始化图表')
    initCompletionTrendChart()
    initCategoryPieChart()
    initPriorityChart()
    
    // 再次调整图表大小以适应容器
    handleResize()
  }, 300)
  
  window.addEventListener('resize', handleResize)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize)
  trendChartInstance?.dispose()
  pieChartInstance?.dispose()
  priorityChartInstance?.dispose()
})
</script>

<style scoped>
.dashboard-view {
  width: 100%;
  height: 100%;
  overflow: hidden;
}

.loading-container {
  padding: 1rem;
}

.dashboard-summary {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 1rem;
  margin-bottom: 1.5rem;
}

.summary-card {
  background-color: white;
  border-radius: 8px;
  padding: 1rem;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  text-align: center;
}

.summary-card h3 {
  margin-top: 0;
  margin-bottom: 0.5rem;
  color: #606266;
  font-size: 1rem;
}

.summary-value {
  font-size: 1.8rem;
  font-weight: bold;
  color: #303133;
}

.charts-container {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 1rem;
}

.chart-card {
  background-color: white;
  border-radius: 8px;
  padding: 1rem;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.chart-card h3 {
  margin-top: 0;
  margin-bottom: 0.5rem;
  color: #606266;
  font-size: 1rem;
  text-align: center;
}

.chart {
  height: 250px;
}

@media (max-width: 1200px) {
  .dashboard-summary {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .charts-container {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .dashboard-summary {
    grid-template-columns: 1fr;
  }
}
</style>